package cn.flant.excel.jxl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Sheet;
import jxl.Workbook;

import cn.flant.excel.ExcelHandler;

public class JXLExcelHandler implements ExcelHandler {

	@Override
	public List<String[]> getSheetData(File file, int sheetId) throws Exception{
		Workbook book = null;
		try {
			book = Workbook.getWorkbook(file);
			Sheet sheet = book.getSheet(sheetId);
			return sheetToData(sheet);
		} catch (Exception e) {
			if (e instanceof Exception) {
				throw (Exception) e;
			} else {
				throw new Exception("read sheet data error: " + e.getMessage(),
						e);
			}
		} finally {
			if (book != null) {
				book.close();
			}
		}
	}

	@Override
	public Map<String, List<String[]>> getAllData(File file) throws Exception{
		Workbook book = null;
		try {
			book = Workbook.getWorkbook(file);
			Map<String, List<String[]>> datas = new HashMap<String, List<String[]>>();
			String[] sheetNames = book.getSheetNames();
			for (String sheetName : sheetNames) {
				Sheet sheet = book.getSheet(sheetName);
				List<String[]> data = sheetToData(sheet);
				datas.put(sheetName, data);
			}
			return datas;
		} catch (Exception e) {
			if (e instanceof Exception) {
				throw (Exception) e;
			} else {
				throw new Exception("read sheet data error: " + e.getMessage(),
						e);
			}
		} finally {
			if (book != null) {
				book.close();
			}
		}
	}

	private List<String[]> sheetToData(Sheet sheet) {
		int row = sheet.getRows();
		int col = sheet.getColumns();
		List<String[]> dataList = new ArrayList<String[]>(row);
		for (int j = 0; j < row; j++) {
			String[] data = new String[col];
			for (int k = 0; k < col; k++) {
				data[k] = sheet.getCell(k, j).getContents().trim();
			}
			dataList.add(data);
		}
		return dataList;
	}
}
